package handler

import (
	"context"
	"go_final/mxshop_srvs/goods_srv/global"
	"go_final/mxshop_srvs/goods_srv/model"
	goodspb "go_final/mxshop_srvs/goods_srv/proto/protofile"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"gorm.io/gorm"

	"google.golang.org/protobuf/types/known/emptypb"
)

func (s Server) BrandList(c context.Context, request *goodspb.BrandFilterRequest) (*goodspb.BrandListResponse, error) {
	var brands []model.Brand
	res := global.DB.Scopes(Paginate(int(request.Pages), int(request.PagePerNums))).Find(&brands)

	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Error(codes.Internal, res.Error.Error())
	}

	rsp := goodspb.BrandListResponse{}

	// 查询总条数
	var count int64
	global.DB.Model(&model.Brand{}).Count(&count)
	rsp.Total = int32(count)

	for _, brand := range brands {
		rsp.Data = append(rsp.Data, &goodspb.BrandInfoResponse{
			Id:   brand.ID,
			Name: brand.Name,
			Logo: brand.Logo,
		})
	}

	return &rsp, nil
}

func (s Server) CreateBrand(c context.Context, request *goodspb.BrandRequest) (*goodspb.BrandInfoResponse, error) {
	var brand model.Brand
	res := global.DB.Where(model.Brand{
		Name: request.Name,
	}).First(&brand)
	if res.RowsAffected > 0 {
		return nil, status.Errorf(codes.AlreadyExists, "品牌已存在, 创建品牌失败")
	}

	brand.Name = request.Name
	brand.Logo = request.Logo

	res = global.DB.Create(&brand)
	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Errorf(codes.Internal, res.Error.Error())
	}

	return &goodspb.BrandInfoResponse{
		Id:   brand.ID,
		Name: request.Name,
		Logo: request.Logo,
	}, nil
}

func (s Server) DeleteBrand(c context.Context, request *goodspb.BrandRequest) (*emptypb.Empty, error) {
	res := global.DB.Delete(&model.Brand{}, request.Id)
	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Errorf(codes.Internal, res.Error.Error())
	}

	if res.RowsAffected < 1 {
		return nil, status.Errorf(codes.NotFound, "没有该品牌记录")
	}

	return &emptypb.Empty{}, nil
}

func (s Server) UpdateBrand(c context.Context, request *goodspb.BrandRequest) (*emptypb.Empty, error) {
	brand := &model.Brand{}
	brand.ID = request.Id

	if request.Name != "" {
		brand.Name = request.Name
	}

	if request.Logo != "" {
		brand.Logo = request.Logo
	}

	res := global.DB.Updates(&brand)

	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Errorf(codes.Internal, res.Error.Error())
	}

	if res.RowsAffected < 1 {
		return nil, status.Errorf(codes.NotFound, "没有该品牌记录")
	}

	return &emptypb.Empty{}, nil
}
